<?php
/**
 * +----------------------------------------------------------------------
 * | 模型
 * +----------------------------------------------------------------------
 *                      _ooOoo_
 *                     o8888888o            | AUTHOR: 杜云
 *                     88" . "88            | EMAIL: 987772927@qq.com
 *                     (| -_- |)            | QQ: 987772927
 *                     O\  =  /O            | WECHAT: 987772927
 *                  ____/`---'\____
 *                .'  \\|     |//  `.
 *               /  \\|||  :  |||//  \
 *              /  _||||| -:- |||||-  \
 *              |   | \\\  -  /// |   |
 *              | \_|  ''\-/''  |   |
 *              \  .-\__  `-`  ___/-. /
 *            ___`. .'  /-.-\  `. . __
 *         ."" '<  `.___\_<|>_/___.'  >'"".
 *        | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *        \  \ `-.   \_ __\ /__ _/   .-` /  /
 *   ======`-.____`-.___\_____/___.-`____.-'======
 *                      `=-='
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace App\Model;

use Qbhy\HyperfAuth\AuthAbility;
use Qbhy\HyperfAuth\Authenticatable;
use Hyperf\Database\Model\SoftDeletes;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Cache\Annotation\CacheEvict;

class User extends BaseModel implements Authenticatable
{
    use AuthAbility;
    protected $table = 'users';

    protected $fillable = ['dept_id','mid','type','realname','age','phone','idcard','account','nickname','avatar','gender','password','license_number','driving_experience','driving_type','validity_start','validity_end','driver_status','introduction','login_times','last_login_ip','last_login_time','salt','email','status','created_user','created_at','updated_at'];

    protected $casts = ['id' => 'integer','dept_id' => 'integer','type' => 'integer','driver_status' => 'integer','mid' => 'integer','age' => 'integer','status' => 'integer','created_user' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime'];

    protected $hidden = [
        'password','deleted_at','salt'
    ];
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = encryptPassword($value);
    }
    public function getRoleIdsAttribute()
    {
        return $this->roles()->pluck('id')->toArray();
    }
    public function getId()
    {
        // 返回用户id
        return $this->id;
    }

    public static function retrieveById($key): ?Authenticatable
    {
        // 通过id查找用户
        return self::query()->find($key);
    }
    public function roles()
    {
        return $this->belongsToMany(Roles::class, 'users_roles', 'user_id', 'role_id');
    }
    public function dept()
    {
        return $this->hasOne(Depts::class, 'id', 'dept_id');
    }
    /**
     * [org 机构]
     * @return [type] [description]
     */
    public function org()
    {
        return $this->hasOne(Institution::class, 'id', 'mid');
    }
    /**
     * [getUserInfo description]
     * @param  [type] $user [description]
     * @return [type]       [description]
     * @Cacheable(prefix="UserInfo",ttl=9000, value="#{user.id}",listener="UserInfo")
     */
    public static function getUserInfo($user = null):array
    {
        $_authList = [];$roles = [];
        if(!$user) return $_authList;
        $configs = Config::pluck('value','name');
        if ($user->account == config('super_admin')){
            $_authList = Menus::query()->where(['status'=>1])->orderBy('id','asc')->orderBy('sort','asc')->pluck('name')->toArray();
            $roles[] = '超级管理员';
        }else{
            foreach ($user->roles()->get() as $key => $item) {
                $roles[] = $item['name'];
                $_authList = array_merge(($_authList?:[]),$item->menus()->where(['status'=>1])->orderBy('id','asc')->orderBy('sort','asc')->pluck('name')->toArray());
            }
            $cc = Institution::where('id',$user->mid)->value('config');
            $configs = $cc?json_decode($cc,true):[];
        }
        $user['console_auth'] = (in_array(1,(array) $user->role_ids) || in_array(3,(array) $user->role_ids) || in_array(5,(array) $user->role_ids) || $user->account == config('super_admin'))?1:0;
        $user['roles'] = $roles;
        $user['configs'] = $configs;
        $user['org'] = $user->org()->first()?:[];
        $user['permissionList'] = array_filter($_authList, 'strlen');
        return $user->toArray();
    }
    /**
     * [updateUserInfo description]
     * @param  array $input [description]
     * @return bool       [description]
     * @CacheEvict(prefix="UserInfo",value="#{input.id}")
     */
    public static function updateUserInfo($input = []):bool
    {
        $ret = User::saveInfo($input);
        if($ret) return true;
        return false;
    }
    /**
     * [team ]
     * @return [type] [description]
     */
    public function team()
    {
        return $this->belongsToMany(Team::class,'teams_users','uid','tid');
    }
}
